import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

public class Com {
	int port;
	InetAddress multicastAddress;
	MulticastSocket socket;
	
	public Com(int p , String am){
		port = p;
		try {
			socket = new MulticastSocket(port);
			multicastAddress = InetAddress.getByName(am);
			socket.joinGroup(multicastAddress);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void send(ByteBuffer byteBuf){//exo 3
		byte[] buf = byteBuf.array();
		
		DatagramPacket dp = new DatagramPacket(buf, byteBuf.position(), multicastAddress, port);
		
		try {
			socket.send(dp);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void receive(ByteBuffer byteBuf){//exo 4
		byte[] buf = byteBuf.array();
		DatagramPacket packet = new DatagramPacket(buf, buf.length);

		try {
			socket.receive(packet);
			byteBuf.put(packet.getData());
			byteBuf.limit(packet.getLength());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	static String getString(ByteBuffer b, int len){//exo 2
		byte[] t = b.array();
		return new String(t, 0, len);
	}
}
